import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Result, Button } from 'antd';
import { useAuthStore } from '../../stores/auth';

interface PermissionGuardProps {
  children: React.ReactNode;
  requiredPermissions?: string[];
  requiredRoles?: string[];
  fallback?: React.ReactNode;
  skipInDev?: boolean;
  // 新增：权限验证上下文
  permissionContext?: any;
  // 新增：高级权限验证函数
  customPermissionCheck?: (user: any, context?: any) => boolean;
}

const PermissionGuard: React.FC<PermissionGuardProps> = ({
  children,
  requiredPermissions = [],
  requiredRoles = [],
  fallback,
  skipInDev = true,
  permissionContext,
  customPermissionCheck,
}) => {
  const { isAuthenticated, user, hasPermission, hasRole, login } = useAuthStore();
  const location = useLocation();

  const isDevelopment = import.meta.env.DEV;
  
  // 开发环境跳过权限检查
  if (isDevelopment && skipInDev) {
    return <>{children}</>;
  }

  // 处理未认证用户
  if (!isAuthenticated) {
    if (isDevelopment) {
      console.log('🔑 开发环境：自动模拟登录');
      const mockUser = {
        id: 'dev-user-001',
        username: 'developer',
        email: 'dev@v3cloud.com',
        avatar: '',
        roles: ['admin', 'user', 'developer'],
        permissions: [
          'user:read', 'user:create', 'user:update', 'user:delete',
          'role:read', 'role:create', 'role:update', 'role:delete',
          'permission:read', 'permission:create', 'permission:update', 'permission:delete',
          'system:read', 'system:update',
          'dashboard:read',
          'profile:read', 'profile:update'
        ],
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
      };
      
      login('dev-mock-token', mockUser);
      
      return <>{children}</>;
    }
    
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  if (requiredRoles.length > 0) {
    const hasRequiredRole = requiredRoles.some(role => hasRole(role));
    if (!hasRequiredRole) {
      if (isDevelopment) {
        console.warn('⚠️ 权限检查失败：缺少角色权限', {
          required: requiredRoles,
          current: user?.roles || [],
          path: location.pathname
        });
      }
      
      return fallback || (
        <Result
          status="403"
          title="403"
          subTitle={
            isDevelopment 
              ? `开发环境：缺少角色权限 [${requiredRoles.join(', ')}]，当前角色：[${user?.roles?.join(', ') || '无'}]`
              : "抱歉，您没有权限访问此页面。"
          }
          extra={
            <div>
              <Button type="primary" onClick={() => window.history.back()}>
                返回上页
              </Button>
              {isDevelopment && (
                <Button 
                  style={{ marginLeft: 8 }}
                  onClick={() => {
                    console.log('当前用户信息：', user);
                    console.log('需要的角色：', requiredRoles);
                  }}
                >
                  查看权限信息
                </Button>
              )}
            </div>
          }
        />
      );
    }
  }

  // 自定义权限检查
  if (customPermissionCheck) {
    const hasCustomPermission = customPermissionCheck(user, permissionContext);
    if (!hasCustomPermission) {
      if (isDevelopment) {
        console.warn('⚠️ 自定义权限检查失败', {
          user,
          context: permissionContext,
          path: location.pathname
        });
      }
      
      return fallback || (
        <Result
          status="403"
          title="403"
          subTitle={
            isDevelopment 
              ? `开发环境：自定义权限检查失败`
              : "抱歉，您没有权限访问此功能。"
          }
          extra={
            <div>
              <Button type="primary" onClick={() => window.history.back()}>
                返回上页
              </Button>
              {isDevelopment && (
                <Button 
                  style={{ marginLeft: 8 }}
                  onClick={() => {
                    console.log('用户信息：', user);
                    console.log('权限上下文：', permissionContext);
                  }}
                >
                  查看权限信息
                </Button>
              )}
            </div>
          }
        />
      );
    }
  }

  if (requiredPermissions.length > 0) {
    // 支持带上下文的权限检查
    const hasRequiredPermission = requiredPermissions.some(permission => {
      if (permissionContext) {
        // 如果有上下文，使用增强的权限检查
        return hasPermission(permission, permissionContext);
      } else {
        // 向后兼容的基础权限检查
        return hasPermission(permission);
      }
    });
    
    if (!hasRequiredPermission) {
      if (isDevelopment) {
        console.warn('⚠️ 权限检查失败：缺少具体权限', {
          required: requiredPermissions,
          current: user?.permissions || [],
          context: permissionContext,
          path: location.pathname
        });
      }
      
      return fallback || (
        <Result
          status="403"
          title="403"
          subTitle={
            isDevelopment 
              ? `开发环境：缺少权限 [${requiredPermissions.join(', ')}]${permissionContext ? '（带上下文检查）' : ''}，当前权限：[${user?.permissions?.join(', ') || '无'}]`
              : "抱歉，您没有权限访问此功能。"
          }
          extra={
            <div>
              <Button type="primary" onClick={() => window.history.back()}>
                返回上页
              </Button>
              {isDevelopment && (
                <Button 
                  style={{ marginLeft: 8 }}
                  onClick={() => {
                    console.log('当前用户信息：', user);
                    console.log('需要的权限：', requiredPermissions);
                    console.log('权限上下文：', permissionContext);
                  }}
                >
                  查看权限信息
                </Button>
              )}
            </div>
          }
        />
      );
    }
  }

  return <>{children}</>;
};

export default PermissionGuard;